package com.beauty.controller;

import com.beauty.dto.BeautyResponse;
import com.beauty.dto.ResponseList;
import com.beauty.dto.comment.GetCommentListData;
import com.beauty.dto.comment.InsertCommentData;
import com.beauty.mapper.ICommentMapper;
import com.beauty.mapper.IUserMapper;
import com.beauty.services.MyBaitsHelp;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("api/comment")
public class CommentController {
    private final MyBaitsHelp myBaitsHelp;

    CommentController(MyBaitsHelp myBaitsHelp) {
        this.myBaitsHelp = myBaitsHelp;
    }

    /**
     * 插入评论
     *
     * @param data
     * @param cookieUserId
     * @return
     */
    @PostMapping("/insertComment")
    public BeautyResponse<ResponseList<String>> insertComment(@RequestBody() InsertCommentData data, @CookieValue(name = "userId", defaultValue = "") String cookieUserId) {
        var res = new BeautyResponse<ResponseList<String>>();
        var uuid = UUID.randomUUID().toString();
        // 开始数据库操作
        try (var session = this.myBaitsHelp.factory.openSession()) {
            session.getMapper(ICommentMapper.class).insertComment(uuid, data.noteId, data.content, new Date().getTime(), 0, "", cookieUserId);
            res.message = "插入成功";
        } catch (Error e) {
            res.message = e.getMessage();
        }
        return res;
    }


    /**
     * 获得评论列表
     *
     * @param pageIndex
     * @param pageSize
     * @return
     */
    @GetMapping("/getCommentList")
    public BeautyResponse<ResponseList<GetCommentListData>> getCommentList(@RequestParam(defaultValue = "1") int pageIndex, @RequestParam(defaultValue = "1") int pageSize, @RequestParam(defaultValue = "1") String noteId) {
        var res = new BeautyResponse<ResponseList<GetCommentListData>>();
        res.response = new ResponseList<GetCommentListData>();
        res.response.data =  new ArrayList<>();
        // 开始数据库操作
        try (var session = this.myBaitsHelp.factory.openSession()) {
            var comment = session.getMapper(ICommentMapper.class).getCommentList((pageIndex - 1) * pageSize, pageSize, noteId);
            comment.forEach(c -> {
                var com = new GetCommentListData();
                var user = session.getMapper(IUserMapper.class).selectUserById(c.userId);
                var count = session.getMapper(ICommentMapper.class).getCommentListCount(noteId);
                com.content = c.content;
                com.createDate = c.createDate;
                com.id = c.id;
                com.favoriteCount = c.favoriteCount;
                com.userId = c.userId;
                com.userName = user.name;
                com.avatar = user.avatar;
                res.response.count = count;
                res.response.data.add(com);
            });
        } catch (Error e) {
            res.message = "失败";
        }
        return res;
    }


}
